package com.hmall.order.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.feign.client.ItemClient;
import com.hmall.item.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Component

public class TimeJob {

    @Autowired
    ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Scheduled(cron= "0 * * * * ?")
    public void ordertime(){
        Date date = new Date();
        date.setTime(date.getTime()-1000*60*30);
        List<Order> list=new ArrayList();
        list=orderMapper.selectList(Wrappers.<Order>query().eq("status",0).lt("create_time",date));
        if(list.size()>0&&list!=null){
            for (Order order : list) {
                order.setCloseTime(new Date());
                order.setStatus(1);
                OrderDetail orderDetail=orderDetailMapper.selectByOrderId(order.getId());
              Long id=orderDetail.getItemId();
              Item item=itemClient.queryItemById(id);
              item.setStock(item.getStock()+orderDetail.getNum());
              itemClient.updateStock(id,orderDetail.getNum()-orderDetail.getNum()*2);

                orderMapper.updateById(order);
                log.info(order.getId()+"订单超时已关闭");
            }

        }
    }
}
